package com.suxii.netty_demo.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.scwang.smart.refresh.header.BezierRadarHeader;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.suxii.adapter.FriendListAdapter;
import com.suxii.netty_demo.R;
import com.suxii.netty_demo.activity.NewFriendActivity;
import com.suxii.netty_demo.activity.Suxii;
import com.suxii.service.MyNettyService;
import com.suxii.utils.Global;
import com.suxii.widget.dialog.CustomDialog;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FriendFragment extends Fragment {
    private Context context;

    public FriendFragment(Context context) {
        this.context = context;
    }

    private RecyclerView friendList;
    private FriendListAdapter friendListAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_friend, container, false);

        friendList=view.findViewById(R.id.friend_list);


        LinearLayoutManager manager=new LinearLayoutManager(context);
        friendList.setLayoutManager(manager);

        findFriend();
        setLond(view);

        Intent intent=new Intent(context, MyNettyService.class);
        context.startService(intent);

        // 新朋友监听事件
        newFriend(view);

        return view;
    }

    public static TextView friendCircleText=null;
    public void newFriend(View view){
        view.findViewById(R.id.friend_newfriend).setOnClickListener(v->{
            Intent intent=new Intent(context, NewFriendActivity.class);
            context.startActivity(intent);
            //Toast.makeText(context, Global.newFriendList.size()+"", Toast.LENGTH_SHORT).show();
        });

        // 初始化新朋友数量
        friendCircleText = view.findViewById(R.id.friend_circle_text);
        friendCircleText.setText(Global.newFriendList.size()+"");
    }


    /*
    初始化，请求获取好友
     */
    private void init(){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(getString(R.string.url)+"get-friend?uid="+ Global.uid)
                .get()
                .build();
        Call call = client.newCall(request);
        try {
            Response execute = call.execute();
            String s = execute.body().string();
            JsonObject jsonObject = new Gson().fromJson(s, JsonObject.class);
            String data =String.valueOf(jsonObject.get("data"));

            JsonArray jsonArray = new Gson().fromJson(data, JsonArray.class);

            List<String> list=new ArrayList<>();
            for (JsonElement element : jsonArray) {
                JsonObject object = new Gson().fromJson(element, JsonObject.class);
                String s1 = object.get("name") + " " + object.get("uid");
                list.add(s1.replace("\"", ""));

            }

            //String[] uuid = new Gson().fromJson(data, String[].class);
            friendList.post(() -> {
                friendListAdapter = new FriendListAdapter(list, context);
                friendList.setAdapter(friendListAdapter);

                // 列表长按事件
                friendListAdapter.setOnItemLongListener((v,name,uid) -> {
                    showPopupWindow(v,name,uid);
                    return true;
                });
                savaFriend(list);
                //findFriend();
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    将请求的好友储存在本地
     */
    private boolean savaFriend(List<String> uuid){
        File file = new File(context.getFilesDir(), "friend.sx");
        try(var fos=new FileOutputStream(file);
            var bw=new BufferedWriter(new OutputStreamWriter(fos))) {
            uuid.forEach(u->{
                try {
                    bw.write(u);
                    bw.newLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /*
    读取本地好友
     */
    private void findFriend(){
        File file = new File(context.getFilesDir(), "friend.sx");
        // 本地有缓存就加载本地，否就请求好友
        if (file.isFile()) {

            try (var fis = new FileInputStream(file);
                 var br = new BufferedReader(new InputStreamReader(fis))
            ) {
                String data;
                List<String> uuid = new ArrayList<>();
                while ((data = br.readLine()) != null) {
                    uuid.add(data);
                }
                //添加列表
                friendListAdapter = new FriendListAdapter(uuid, context);
                friendList.setAdapter(friendListAdapter);

                // 列表长按事件
                friendListAdapter.setOnItemLongListener((v,name,uid) -> {
                    showPopupWindow(v,name,uid);
                    return true;
                });
                // 开启服务
                //Intent intent=new Intent(context, MyNettyService.class);
                //context.startService(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            new Thread(this::init).start();
        }

    }

    private void setLond(View view) {
        RefreshLayout refreshLayout = view.findViewById(R.id.refreshLayout2);

        refreshLayout.setRefreshHeader(new ClassicsHeader(context));
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(1500);
                new Thread(FriendFragment.this::init).start();
            }
        });

    }


    private PopupWindow popupWindow;

    // 显示弹窗
    private void showPopupWindow(View anchorView,String name,int uid) {
        // 加载弹窗布局
        View popupView = LayoutInflater.from(context).inflate(R.layout.popup_friend, null);

        // 创建PopupWindow对象
        popupWindow = new PopupWindow(popupView, anchorView.getWidth()/3, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        // 设置弹窗的一些属性
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);

        popupView.setOnClickListener(v->{

            dialog(name, uid);
            mDialog.show();
            popupWindow.dismiss();
        });

        // 显示弹窗
        popupWindow.showAsDropDown(anchorView,anchorView.getWidth()/3,-anchorView.getHeight()/3);

    }

    private CustomDialog mDialog;
    private void dialog(String name,int uid){
        mDialog=new CustomDialog(context, "温馨提示", "点击确定将删除好友:"+name+"("+uid+")", "确定", v -> {
            mDialog.dismiss();
            new Thread(()->deleteUid(uid),"删除好友").start();
        }, "取消");
    }

    private void deleteUid(int uuid) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(getString(R.string.url)+"delete-friend?uid="+Global.getUid()+"&uuid="+uuid)
                .build();
        Call call = client.newCall(request);
        try {
            String res = call.execute().body().string();
            JsonObject object = new Gson().fromJson(res, JsonObject.class);
            if (String.valueOf(object.get("msg")).equals("1")) {
                // 请求成功
                new Thread(this::init).start();
            }
            Log.e("aa",res);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
